<template>
<!--  TODO 邀请成员加入 -->
  <el-dialog v-model="visible" destroy-on-close width="760px" :close-on-click-modal="false" @close="close">
    <template #header>
      <div class="my-header">
        <h2>邀请加入 {{treeData[0].label}}</h2>
        <span>您可以通知/邀请公司同事/外部协助者加入到部门组，从而实现协作。</span>
      </div>
    </template>
    <div class="">
      <el-form :model="formData" :rules="formRules" size="small" ref="inviteMemberFormRef" class="drawer-form">
        <el-form-item prop="group" label="加入的部门组：" label-width="110px">
          <el-cascader :disabled="notSetting" style="width: 300px" v-model="formData.group" :options="treeData" ref="userSelectDept" placeholder="请选择管理组"
                       :props="cascaderProps"  @change="selectDept">
          </el-cascader>
          <span style="margin-left: 10px">权限范围：</span>
        </el-form-item>
        <el-form-item label="管理员身份：" prop="identity" label-width="110px">
          <div style="width: 160px;float: left;margin-right: 20px">
            <el-select :disabled="notSetting" v-model="formData.identity" style="width: 150px;" size="small" placeholder="请选择" class="identity">
              <el-option v-for="item in identityOption" :label="item.label" :value="item.value"/>
            </el-select>
          </div>

          <div style="width: 400px;float: left">
            <span >组员:仅查看自己的事务，不具备管理组的权利。</span>
            <span >群主:可查看所处本组及管辖的下层级组的成员事务，具备管理组的权利</span>
          </div>
        </el-form-item>

        <div class="select-state">
          <div class="item" :class="{isActive:formData.shareType === '0'}" @click="shareTypeOpt('0')">邀请链接</div>
          <div class="item" :class="{isActive:formData.shareType === '1'}" @click="shareTypeOpt('1') ">添加手机号码</div>
        </div>

        <el-card class="box-card" v-if="formData.shareType === '0'">
          <span style="font-size: 12px;font-weight: bold;margin-left: 10px">邀请设置</span>
          <div style="margin-top: 20px;margin-left: 20px">
            <p>设置邀请有效期
              <el-tooltip effect="light" content="提示" placement="top-start">
                <el-icon style="font-size:18px;position: relative;top:4px;left:6px"><ele-QuestionFilled /></el-icon>
              </el-tooltip>
            </p>
            <el-select :disabled="notSetting" v-model="formData.lifespan" style="width: 200px;" size="small" placeholder="请选择" clearable>
              <el-option v-for="item in validityOption" :label="item.label" :value="item.value"/>
            </el-select>

            <el-switch
                :disabled="notSetting"
                v-model="formData.isApprove"
                active-value="1"
                inactive-value="0"
                class="mb-2"
                active-text="需管理员审批"
                style="margin-left: 50px"
            />
            <el-tooltip effect="light" content="提示" placement="top-start">
              <el-icon style="font-size:18px;position: relative;top:4px;left:6px"><ele-QuestionFilled /></el-icon>
            </el-tooltip>

            <div class="invite">
              <p class="company">邀请你加入广州英地绿壳科技有限公司，区号为 +86 的手机号可通过此链接</p>
              <span class="url">{{url}}</span>
              <el-button link icon="ele-Refresh" size="small" @click="refreshUrl(inviteMemberFormRef)" style="margin-left: 10px;color: #409eff;">{{url!=null?'重新生成':'生成链接'}}</el-button>
              <el-button type="primary" link icon="ele-CopyDocument" size="small" v-if="url!=null" @click="copyText" style="margin-left: 10px;">复制</el-button>
            </div>
          </div>
        </el-card>

        <el-card class="box-card" v-if="formData.shareType === '1'">
          <div v-for="(item,index) in formData.inviteInfo" :key="item.id" style="margin-bottom: 10px">
            <el-input v-model="item.phone" placeholder="请输入手机号" style="width: 50%" maxlength="11" @change="checkIshas(item)">
              <template #prepend>+86</template>
            </el-input>
            <el-input v-model="item.name" placeholder="请输入姓名" style="width: 40%"/>
            <el-button link icon="ele-CloseBold" size="small" @click="removeInviteInfo(index)" style="margin-left: 10px;"/>
            <div v-if="item.isCheck">
              <span style="color:red;font-size: 12px;">该用户已存在，当前组</span>
           </div>
          </div>
          
          <el-button type="primary" icon="ele-CirclePlus" size="small" @click="addInviteInfo" style="margin-left: 10px;">{{formData.inviteInfo.length > 0?'继续添加':'添加用户' }}</el-button>
          <el-button icon="ele-FirstAidKit" size="small" @click="inviteByPersonnel" style="margin-left: 10px;">人事架构选人</el-button>
        </el-card>
      </el-form>
    </div>
    <template #footer>
          <span class="dialog-footer">
            <el-button size="small" @click="cancel(inviteMemberFormRef)">关闭</el-button>
            <el-button size="small" type="primary" icon="ele-Check" @click="refreshUrl(inviteMemberFormRef)" v-if="formData.shareType === '1'">提交</el-button>
          </span>
    </template>
  </el-dialog>


  <!-- 从人事选择人员 start -->

  <el-dialog title="选择人员" v-model="dialogOtherVisible" width="30%" :before-close="handleRoleClose">
    <el-table
        ref="multipleTableRef"
        :data="oaStaffTableData"
        style="width: 100%"
        size="small"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column property="name" label="姓名" width="120"/>
      <el-table-column property="phone" label="手机号"/>
    </el-table>

    <div class="page-block">
      <el-pagination v-model:currentPage="queryData.current" v-model:page-size="page" :page-sizes="[10, 20, 30, 40]"
                     :small="true" :disabled="false" :background="false"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total" :hide-on-single-page="true" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"/>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="dialogOtherVisible = false">取 消</el-button>
      <el-button size="small" type="primary" @click="selectUserByOaStaff">确 定</el-button>
    </span>
  </el-dialog>
  <!-- 从人事选择人员 end -->

</template>

<script>
import {computed, reactive, ref, toRefs} from "vue";
import {ElMessage} from "element-plus";
import {inintUrl} from "/@/api/sys/dept"
import {getPage} from "/@/api/oa/staff"
export default {
  name: "InviteMember",
  emits:['onSubmit','update:dialogDrawer'],
  props: {
    dialogDrawer: {
      type: Boolean,
      default: true,
    },
    treeData:{
      type: Array,
      default: null,
    }
  },
  setup(props, context) {
    let inviteMemberFormRef = ref()
    const userSelectDept = ref()
    const { dialogDrawer, treeData } = toRefs(props)
    let visible = computed({
      get: () => {
        if (dialogDrawer.value){
          initData()
          state.dialogDrawer = true
        }
        return dialogDrawer.value
      },
      set: val => context.emit('update:dialogDrawer', val)
    })
    const state = reactive({
      url: null,
      formData:{
        group:[],
        identity:'0',
        lifespan:'',//有效期
        isApprove:'0',
        inviteInfo:[],
        deptId:null,
        shareType: "0"
      },
      formRules:{
        group:[{ required: true, trigger: 'change', message: '请选择管理组'}],
        identity:[{ required: true, trigger: 'change', message: '请选择成员身份'}],
      },
      groupOption:[],
      validityOption:[],
      identityOption:[
        {
          label:'群主',
          value:'1'
        },
        {
          label:'组员',
          value:'0'
        }

      ],
      cascaderProps: {
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true
      },
      notSetting:false,
      shareKey:null,
      // 从人事选择人员
      dialogOtherVisible: false,
      queryData: {
        current: 1,
        size: 10,
        state: 4,
        phone: null,
        name: null
      },
      oaStaffTableData: [],
      total: 10,
      page: 10,
      selectPersons: [],
      multipleSelection: [],
      persons:[]
    })

    //关闭时触发
    const close = () => {
      context.emit('update:dialogDrawer', false)
    }
    //提交
    const submit = (formEl) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (!valid) return // 必填没有填就直接结束
        context.emit('onSubmit', true)
      })
    }
    //取消
    const cancel = (formEl) => {
      if (!formEl) return
      formEl.resetFields()
      context.emit("update:dialogDrawer", false)
    }
    //刷新邀请URL
    const refreshUrl = (inviteMemberFormRef) => {

      inviteMemberFormRef.validate((valid) => {
        if (valid) {
          // 防止重复生成，需要删除旧的
          if(state.shareKey !=null){
            state.formData.count = 1
            state.formData.oldShareKey = state.shareKey
          }else {
            state.formData.count = 0
          }
          state.formData.deptId = state.formData.group.length > 0 ? state.formData.group[state.formData.group.length - 1] : "0"

          if(state.formData.shareType == '1' && state.formData.inviteInfo.length > 0){
             for(let i of  state.formData.inviteInfo){
                i.deptId = state.formData.deptId
             }
          }

          inintUrl(state.formData).then(res=>{
            if(res.code == 0){
              if(state.formData.shareType == '1' ){
                ElMessage.success('保存成功！')
              }else{
                state.url = document.location.origin +"/r?shareKey="+res.data
                state.shareKey = res.data
              }
            }

          })
        } else {
          return false;
        }
      });


    }
    //复制文本
    const copyText = () => {
      navigator.clipboard.writeText(state.url).then(function() {
        //复制成功
        console.log("复制成功")
      },function() {
        //复制失败 使用旧版
        const textarea = document.createElement('textarea');
        textarea.value = state.url;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');//被弃用 但是兼容
        document.body.removeChild(textarea);
      })
      ElMessage.success("复制成功")
    }
    //删除邀请人信息
    const removeInviteInfo = (index) => {
      state.formData.inviteInfo.splice(index, 1)
    }
    //添加邀请人信息
    const addInviteInfo = () => {
      state.formData.inviteInfo.push(
          {
            id: null,
            deptId: null,
            oaStaffId: null,
            name:'',
            phone:''
          }
      )
    }
    //人事架构选人

    const getOAStaffList = () => {
      getPage(state.queryData).then(res => {
        state.oaStaffTableData = res.data.records
        state.total = res.data.total
      })
    }

    const inviteByPersonnel = () => {
      state.dialogOtherVisible = true
      state.multipleSelection = []
      state.queryData.current = 1
      getOAStaffList()
    }
    const handleSelectionChange = (val) => {
      state.multipleSelection = val
    }
    const handleSizeChange = e => {
      state.queryData.size = e
      getOAStaffList()
    }

    const handleCurrentChange = e => {
      state.queryData.current = e
      getOAStaffList()
    }
    //数据初始化
    const initData = () => {
      state.validityOption = []
      for (let i = 1; i <= 6; i++) {
        state.validityOption.push(
            {
              label: i*10 + '天后过期',
              value:i*10
            },
        )
      }
      state.validityOption.push(
          {
            label:'永不过期',
            value:0
          },
      )
      state.formData.inviteInfo = []
    }


    const shareTypeOpt = (value) => {
      state.formData.shareType  = value
    }

    const selectUserByOaStaff = () => {
      
      state.dialogOtherVisible = false
      if (state.multipleSelection != null && state.multipleSelection.length > 0) {
        for (let oastaff of state.multipleSelection) {
          let user = {
            id: oastaff.userId,
            deptId: null,
            oaStaffId: oastaff.id,
            name:oastaff.name,
            phone:oastaff.phone
          }
          
          //判断原本是否已存在
          const index = state.persons.findIndex(e => e.phone === user.phone)
          if (index < 0) {
            user.isCheck = false
          }else{
            user.isCheck = true
          }
          state.formData.inviteInfo.push(user)
        }
      }
    }

    const selectDept = (value) => {
      state.persons = []
      let data = userSelectDept.value.getCheckedNodes()[0].data
      inintPersons(data)
    }

    const inintPersons = (data) => {
      console.log(data)
      if (data.sysUsers != null && data.sysUsers.length > 0) {
        for (let su of data.sysUsers) {
          let user = {
            id: null,
            deptId: null,
            oaStaffId: null,
            name:su.nickname,
            phone:su.phone
          }
          state.persons.push(user)
        }
        // 未注册的用户
        for (let su of data.sysDeptStaffs) {
          let user = {
            id: null,
            deptId: null,
            oaStaffId: null,
            name:su.name,
            phone:su.phone
          }
          state.persons.push(user)
        }

      }
    }

    const checkIshas = (data) =>{
        const index = state.persons.findIndex(e => e.phone === data.phone)
        if (index < 0) {
            data.isCheck = false
          }else{
            data.isCheck = true
          }
          console.log(data.isCheck)
    }

    return{
      ...toRefs(state),
      dialogDrawer,
      visible,
      inviteMemberFormRef,
      treeData,
      close,
      submit,
      cancel,
      refreshUrl,
      copyText,
      removeInviteInfo,
      addInviteInfo,
      inviteByPersonnel,
      initData,
      shareTypeOpt,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      selectUserByOaStaff,
      userSelectDept,
      selectDept,
      inintPersons,
      checkIshas
    }
  }
}
</script>

<style scoped lang="scss">
.drawer-form{
  .tips{
    display: flex;
    flex-direction: column;
    margin-left: 30px;
  }

  .identity-select{
    span{
      width: 110px;
      text-align: right;
      padding: 0 12px 0 0;
    }

    .identity{

    }
  }

  .select-state {
    display: flex;
    justify-content: space-evenly;
    margin-bottom: 30px;

    .item {
      font-size: 15px;
      font-weight: bold;
      cursor: pointer;
    }

    .item:hover {
      color: #18a058;
    }

    .isActive {
      border-bottom: 3px solid #4aa71c;
      color: #18a058;
    }
  }

  .invite{
    margin-top: 20px;

    .company{
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 10px;
    }
    .url{
      font-size: 13px;
      text-decoration:underline
    }
  }
}

</style>
